package com.exsun.ex1077.ui.activity.device

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.KeyboardUtils
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.grid
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.exsun.ex1077.R
import com.exsun.ex1077.app.Constant
import com.exsun.ex1077.databinding.ActivityDeviceAddBinding
import com.exsun.ex1077.extend.toPhotoUrl
import com.exsun.ex1077.model.Device
import com.exsun.ex1077.model.Icon
import com.exsun.ex1077.ui.activity.search.SearchActivity
import com.exsun.ex1077.ui.popup.IconSelectPopup
import com.exsun.ex1077.ui.popup.MsgPopup
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import com.lxj.xpopup.XPopup
import com.zhangping.fastjetpack.base.BaseActivity
import com.zhangping.fastjetpack.binding.gone
import com.zhangping.fastjetpack.binding.visible
import com.zhangping.fastjetpack.callback.OneCallback
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.base.parseState
import com.zhangping.fastjetpack.extend.view.clickNoRepeat
import com.zhangping.fastjetpack.extend.view.textString
import com.zhangping.fastjetpack.model.Item
import com.zhangping.fastjetpack.ui.popup.MultiSelectPopup
import com.zhangping.fastjetpack.ui.popup.TreeSingleSelectPopup
import com.zhangping.fastjetpack.utils.GlideEngine
import com.zhangping.hwscan.ui.activity.ScanCodeActivity
import kotlinx.android.synthetic.main.activity_device_add.*

/**
 * 描述：添加/编辑设备
 * 作者：ZhangPing
 * 创建时间：2023/3/24 14:11
 */
class DeviceAddActivity: BaseActivity<DeviceAddViewModel, ActivityDeviceAddBinding>() {

    override fun title() = if (isUpdateMode()) "设备编辑" else "设备新增"
    override fun barBgColor() = R.color.transparent

    private var deviceModelPosition = -1
    private var manageTypePosition = -1
    //公司选择弹窗
    private lateinit var companySelectPopup: TreeSingleSelectPopup
    //视频通道弹窗
    private lateinit var videoChannelPopup: MultiSelectPopup
    //设备图标弹窗
    private lateinit var iconSelectPopup: IconSelectPopup
    //设备信息最大可选照片数量
    private val deviceInfoMaxSelectNum = 3
    //负责人信息最大可选照片数量
    private val personInfoMaxSelectNum = 1
    //设备号错误信息
    private var deviceNoError: String = ""
    //sim卡错误信息
    private var simIdError: String = ""
    //首次键盘改变
    private var firstKeyboardChange = true

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        mViewModel.apply {
            pageType.set(intent.getIntExtra("pageType", Constant.DEVICE_MANAGE_ADD))
            equipmentId = intent.getStringExtra("equipmentId")
        }
        super.initView(savedInstanceState)
        initPhotoUploadView(objectPhotoListView, deviceInfoMaxSelectNum)
        initPhotoUploadView(personPhotoListView, personInfoMaxSelectNum)
        scanCode.setOnClickListener {
            toActivityForResult<ScanCodeActivity>{
                if (it.resultCode != RESULT_OK) return@toActivityForResult
                val result = it.data?.getStringExtra("scanResult") ?: ""
                deviceNoEdit.apply {
                    setText(result)
                    clearFocus()
                }
                mViewModel.deviceNoCheck(result)
            }
        }
        deviceNoEdit.setOnFocusChangeListener { v, hasFocus ->
            if (!isUpdateMode() && !hasFocus){
                val deviceNo = deviceNoEdit.textString()
                if (deviceNo.isEmpty()){
                    MsgPopup.error(this, "请输入设备号")
                    return@setOnFocusChangeListener
                }
                mViewModel.deviceNoCheck(deviceNo)
            }
        }
        companySelectPopup = XPopup.Builder(this)
            .popupHeight((screenHeight() * 0.5).toInt())
            .autoFocusEditText(false)
            .autoOpenSoftInput(false)
            .asCustom(TreeSingleSelectPopup(this){ item ->
                companyEdit.text = item.text
                mViewModel.companyId.set(item.id)
                resetObjectInfoLayout()
                resetPersonInfoLayout()
            }) as TreeSingleSelectPopup
        companyEdit.setOnClickListener {
            companySelectPopup.show()
        }
        deviceModelEdit.setOnClickListener {
            mViewModel.deviceModelList?.let {
                showCenterList(it.map { it.label }, deviceModelPosition, "选择设备型号"){ position, text ->
                    deviceModelPosition = position
                    mViewModel.deviceModel = mViewModel.deviceModelList!![position].value
                    deviceModelEdit.text = text
                }
            }
        }
        simEdit.setOnFocusChangeListener { v, hasFocus ->
            val simId = simEdit.textString()
            if (!hasFocus) checkSimId(simId)
        }
        objectTypeEdit.setOnClickListener {
            mViewModel.manageTypelList?.let {
                showCenterList(it.map { it.value }, manageTypePosition, "选择监管类型"){ position, text ->
                    manageTypePosition = position
                    objectTypeEdit.text = text
                    initInfoLayout(it[position].key.toInt())
                    personInfoLayout.visible()
                    val manageTypeValue = mViewModel.manageTypelList!![position].key.toInt()
                    if (manageTypeValue != mViewModel.manageType.get()) resetObjectInfoLayout()
                    mViewModel.manageType.set(manageTypeValue)
                }
            }
        }
        val videoChannelList = arrayListOf<Item>()
        for (i in 1..8){
            videoChannelList.add(Item(i.toString(), "CH${i}"))
        }
        videoChannelPopup = XPopup.Builder(this)
            .popupHeight((screenHeight() * 0.5).toInt())
            .autoFocusEditText(false)
            .autoOpenSoftInput(false)
            .asCustom(MultiSelectPopup(this, videoChannelList){ list ->
                videoEdit.text = list.joinToString(",") { it.id }
                mViewModel.videoChannel.set(if (list.isNullOrEmpty()) "" else list.joinToString(",") { it.id })
            }) as MultiSelectPopup
        videoEdit.setOnClickListener {
            videoChannelPopup.show()
        }
        iconSelectPopup = XPopup.Builder(this)
            .asCustom(IconSelectPopup(this, object : OneCallback<Icon>{
                override fun onCall(it: Icon) {
                    deviceIconHint.gone()
                    deviceIconIcon.visible()
                    deviceIconIcon.setImageResource(it.normalId)
                    mViewModel.objectIcon = it.id
                }
            })) as IconSelectPopup
        deviceIconLayout.setOnClickListener {
            iconSelectPopup.show(mViewModel.manageType.get())
        }
        vehicleNoSearch.setOnClickListener {
            if (mViewModel.companyId.get().isEmpty()){
                MsgPopup.error(this, "请先选择所属公司")
                return@setOnClickListener
            }
            toActivityForResult<SearchActivity>(Bundle().apply {
                putInt("pageType", Constant.SEARCH_TYPE_DEVICE_OBJECT)
                putString("companyId", mViewModel.companyId.get())
                putInt("objectTye", mViewModel.manageType.get())
            }){
                if (it.resultCode != RESULT_OK) return@toActivityForResult
                val model = it.data!!.getSerializableExtra("model") as Device
                resetObjectInfoLayout()
                updateInfoLayout(model)
            }
        }
        objectSexEdit.setOnClickListener {
            showCenterList(arrayListOf("男", "女"), mViewModel.objectSex, "选择性别"){ position, text ->
                mViewModel.objectSex = position
                objectSexEdit.text = text
            }
        }
        personSearch.setOnClickListener {
            if (mViewModel.companyId.get().isEmpty()){
                MsgPopup.error(this, "请先选择所属公司")
                return@setOnClickListener
            }
            toActivityForResult<SearchActivity>(Bundle().apply {
                putInt("pageType", Constant.SEARCH_TYPE_DEVICE_PERSON)
                putString("companyId", mViewModel.companyId.get())
            }){
                if (it.resultCode != RESULT_OK) return@toActivityForResult
                val model = it.data!!.getSerializableExtra("model") as Device
                updatePersonLayout(model)
            }
        }
        cancel.setOnClickListener {
            exitConfirm()
        }
        save.clickNoRepeat {
            submit()
        }
        KeyboardUtils.registerSoftInputChangedListener(this) {
            if (firstKeyboardChange){
                firstKeyboardChange = false
                return@registerSoftInputChangedListener
            }
            if (it == 0){
                deviceNoEdit.clearFocus()
                simEdit.clearFocus()
            }
        }
        mViewModel.apply {
            loadDeptTree()
            loadDeviceModel()
            loadManageTypeList()
        }
        if (isUpdateMode()){
            deviceNoEdit.isEnabled = false
            deviceNoEdit.setTextColor(R.color.color_C9C9C9.toColorRes())
            scanCode.gone()
            mViewModel.loadDeviceData()
        }
    }

    private fun isUpdateMode() = mViewModel.pageType.get() != Constant.DEVICE_MANAGE_ADD

    /**
     * 重置对象信息布局
     */
    private fun resetObjectInfoLayout(){
        deviceIconHint.visible()
        deviceIconIcon.gone()
        objectSexEdit.text = ""
        mViewModel.apply {
            objectIcon = null
            objectName.set("")
            objectSex = -1
            objectModel.set("")
            objectColor.set("")
            objectPhotoListView.models = arrayListOf(0)
        }
    }

    /**
     * 重置负责人信息布局
     */
    private fun resetPersonInfoLayout(){
        mViewModel.apply {
            personId.set("")
            personName.set("")
            personTel.set("")
            age.set("")
            idCard.set("")
            personPhotoListView.models = arrayListOf(0)
        }
    }

    /**
     * 数据校验并提交
     */
    private fun submit(){
        if (deviceNoEdit.textString().isEmpty()){
            MsgPopup.error(this, "请输入设备号")
            return
        }
        if (mViewModel.companyId.get().isEmpty()){
            MsgPopup.error(this, "请选择所属公司")
            return
        }
        if (deviceModelEdit.textString().isEmpty()){
            MsgPopup.error(this, "请选择设备型号")
            return
        }
        if (objectTypeEdit.text.isEmpty()){
            MsgPopup.error(this, "请选择监管类型")
            return
        }
        if (deviceIconHint.isVisible){
            MsgPopup.error(this, "请选择设备图标")
            return
        }
        if (deviceNameEdit.text.isEmpty()){
            MsgPopup.error(this, deviceNameEdit.hint.toString())
            return
        }
        if (deviceNoError.isNotEmpty()){
            MsgPopup.error(this, deviceNoError)
            return
        }
        if (simIdError.isNotEmpty()){
            MsgPopup.error(this, simIdError)
            return
        }
        val srcObjectPhoto = (objectPhotoListView.models as List<Any>).filter { it !is Int && (it as String).startsWith("http") }.toMutableList()
        val srcPersonPhoto = (personPhotoListView.models as List<Any>).filter { it !is Int && (it as String).startsWith("http") }.toMutableList()
        val objectPhotoPath = (objectPhotoListView.models as List<Any>).filter { it !is Int && !(it as String).startsWith("http") }
        val personPhotoPath = (personPhotoListView.models as List<Any>).filter { it !is Int && !(it as String).startsWith("http") }
        if (!objectPhotoPath.isNullOrEmpty() && !personPhotoPath.isNullOrEmpty()){
            //两个都需要上传图片
            var uploadFinishCount = 0
            mViewModel.objectPhotoUpload(objectPhotoPath as List<String>).observe(this){
                uploadFinishCount++
                srcObjectPhoto.addAll(it)
                if (uploadFinishCount >= 2) mViewModel.submit(srcObjectPhoto, srcPersonPhoto)
            }
            mViewModel.personPhotoUpload(personPhotoPath as List<String>).observe(this){
                uploadFinishCount++
                srcPersonPhoto.addAll(it)
                if (uploadFinishCount >= 2) mViewModel.submit(srcObjectPhoto, srcPersonPhoto)
            }
        }else if (!objectPhotoPath.isNullOrEmpty()){
            mViewModel.objectPhotoUpload(objectPhotoPath as List<String>).observe(this){
                srcObjectPhoto.addAll(it)
                mViewModel.submit(srcObjectPhoto, srcPersonPhoto)
            }
        }else if (!personPhotoPath.isNullOrEmpty()){
            mViewModel.personPhotoUpload(personPhotoPath as List<String>).observe(this){
                srcPersonPhoto.addAll(it)
                mViewModel.submit(srcObjectPhoto, srcPersonPhoto)
            }
        }else{
            mViewModel.submit(srcObjectPhoto, srcPersonPhoto)
        }
    }

    /**
     * 初始化图片上传View
     */
    private fun initPhotoUploadView(listView: RecyclerView, maxSelectNum: Int){
        listView.grid(3).setup {
            addType<Int> { R.layout.item_device_upload_add }
            addType<String> { R.layout.item_device_upload_photo }
            onClick(R.id.addPhoto, R.id.photo, R.id.delete){
                when(it){
                    R.id.addPhoto -> {
                        //添加照片
                        selectPhoto(maxSelectNum - listView.bindingAdapter.mutable.count { it is String }){
                            val list = listView.bindingAdapter.mutable
                            list.remove(0)
                            list.addAll(it)
                            if (list.size < maxSelectNum) list.add(0)
                            notifyDataSetChanged()
                        }
                    }
                    R.id.photo -> {
                        //预览照片
                        val list = mutable.filter { it is String }.map { LocalMedia().apply { path = it as String } }
                        PictureSelector.create(this@DeviceAddActivity)
                            .themeStyle(com.zhangping.fastjetpack.R.style.picture_default_style)
                            .isNotPreviewDownload(true)
                            .imageEngine(GlideEngine.createGlideEngine())
                            .openExternalPreview(modelPosition, list)
                    }
                    R.id.delete -> {
                        //删除照片
                        mutable.removeAt(modelPosition)
                        notifyItemRemoved(modelPosition)
                        if (!mutable.contains(0)){
                            mutable.add(0)
                            notifyDataSetChanged()
                        }
                    }
                }
            }
        }.models = arrayListOf(0)
    }

    override fun onBackClick(view: View) {
        exitConfirm()
    }

    override fun onBackPressed() {
        exitConfirm()
    }

    private fun exitConfirm(){
        showConfirm("退出将不会保存任何数据，是否确定退出？"){
            finish()
        }
    }

    /**
     * 数据回显
     */
    private fun initUIData(device: Device) {
        mViewModel.apply {
            deviceNo.set(device.deviceId)
            equipmentId = device.equipmentId
            companyId.set(device.companyId)
            companyName.set(device.companyName)
            deviceModel = device.deviceModel
            deviceModelName.set(device.deviceModelStr)
            simId.set(device.simId)
            manageType.set(device.objType)
            manageTypeName.set(device.objTypeStr)
            videoChannel.set(device.channelsNum)
            if (device.objType >= 0 && device.objTypeStr.isNotEmpty()){
                initInfoLayout(device.objType)
                updateInfoLayout(device)
                personInfoLayout.visible()
                updatePersonLayout(device)
            }else{
                resetObjectInfoLayout()
                objectInfoLayout.gone()
                resetPersonInfoLayout()
                personInfoLayout.gone()
            }
        }
    }

    private fun initInfoLayout(objectType: Int){
        objectInfoLayout.visible()
        when(objectType){
            Constant.OBJECT_TYPE_VEHICLE -> {
                deviceNameTitle.text = "车牌号"
                deviceNameEdit.hint = "请选择车牌号"
                objectModelTitle.text = "车辆型号"
                objectModelEdit.hint = "请输入车辆型号"
                deviceColorTitle.text = "车辆颜色"
                deviceColorEdit.hint = "请输入车辆颜色"
            }
            Constant.OBJECT_TYPE_SHIP -> {
                deviceNameTitle.text = "船舶号"
                deviceNameEdit.hint = "请选择船舶号"
                objectModelTitle.text = "船舶型号"
                objectModelEdit.hint = "请输入船舶型号"
                deviceColorTitle.text = "船舶颜色"
                deviceColorEdit.hint = "请输入船舶颜色"
            }
            Constant.OBJECT_TYPE_PERSON -> {
                deviceNameTitle.text = "姓名"
                deviceNameEdit.hint = "请选择姓名"
                objectModelTitle.text = "联系方式"
                objectModelEdit.hint = "请输入联系方式"
                deviceColorTitle.text = "年龄"
                deviceColorEdit.hint = "请输入年龄"
            }
            Constant.OBJECT_TYPE_OBJECT -> {
                deviceNameTitle.text = "物品名称"
                deviceNameEdit.hint = "请选择物品名称"
            }
            Constant.OBJECT_TYPE_ANIMAL -> {
                deviceNameTitle.text = "动物名称"
                deviceNameEdit.hint = "请选择动物名称"
            }
            Constant.OBJECT_TYPE_OTHER -> {
                deviceNameTitle.text = "名称"
                deviceNameEdit.hint = "请选择名称"
            }
        }
    }

    private fun updateInfoLayout(model: Device){
        mViewModel.apply {
            vehicleId = model.vehicleId
            if (!model.objIcon.isNullOrEmpty()){
                deviceIconHint.gone()
                deviceIconIcon.visible()
                deviceIconIcon.setImageResource("object_${model.objIcon}".toDrawableId())
                objectIcon = model.objIcon
            }
            objectName.set(model.numberPlate)
            if (manageType.get() == Constant.OBJECT_TYPE_PERSON){
                if (model.ownerSex >= 0){
                    objectSex = model.ownerSex
                    objectSexEdit.text = if (objectSex == 0) "男" else "女"
                }
                objectModel.set(model.contactNumberVehicle ?: "")
                objectColor.set(model.ageVehicle ?: "")
            }else{
                objectModel.set(model.vehicleModel ?: "")
                objectColor.set(model.vehicleColor ?: "")
            }
            if (!model.vehiclePic.isNullOrEmpty()) {
                val photoList = model.vehiclePic.map { it.path.toPhotoUrl() }
                val newPhotoList = ArrayList<Any>(photoList)
                if (photoList.size < 3) newPhotoList.add(0)
                objectPhotoListView.models = newPhotoList
            }
        }
    }

    private fun updatePersonLayout(model: Device){
        mViewModel.apply {
            personId.set(model.driverId)
            personName.set(model.name)
            personTel.set(model.contactNumber)
            age.set(model.age)
            idCard.set(model.idCard)
            if (!model.driverPic.isNullOrEmpty()) {
                personPhotoListView.models = model.driverPic.map { it.path.toPhotoUrl() }
            }else{
                personPhotoListView.models = arrayListOf(0)
            }
        }
    }

    private fun checkSimId(simId: String){
        if (simId.isNullOrEmpty()){
            simIdError = ""
            return
        }
        if (simId.length != 9 && simId.length != 11 && simId.length != 13 && simId.length != 14 && simId.length != 20) {
            simIdError = "SIM卡号长度为9或11或13或14位或20位"
            MsgPopup.error(this, simIdError)
            return
        }
        mViewModel.simCheck(simId)
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.apply {
            deviceNoCheckResult.observe(this@DeviceAddActivity){
                parseState(it, {
                    it?.let { initUIData(it) }
                    deviceNoError = ""
                },{
                    MsgPopup.error(this@DeviceAddActivity, it.errorMsg)
                    deviceNoError = it.errorMsg
                })
            }
            simCheckResult.observe(this@DeviceAddActivity){
                parseState(it, {
                   simIdError = ""
                }, {
                    MsgPopup.error(this@DeviceAddActivity, it.errorMsg)
                    simIdError = it.errorMsg
                })
            }
            deptTreeResult.observe(this@DeviceAddActivity){
                parseState(it, {
                    companySelectPopup.setNewData(it)
                })
            }
            saveResult.observe(this@DeviceAddActivity){
                parseState(it, {
                    save.isEnabled = false
                    MsgPopup.success(this@DeviceAddActivity, "添加成功")
                    postDelayed(2000){
                        setResult(RESULT_OK, Intent().putExtra("needRefresh", true))
                        finish()
                    }
                })
            }
            updateResult.observe(this@DeviceAddActivity){
                parseState(it, {
                    save.isEnabled = false
                    MsgPopup.success(this@DeviceAddActivity, "更新成功")
                    postDelayed(2000){
                        setResult(RESULT_OK, Intent()
                            .putExtra("needUpdate", true)
                            .putExtra("equipmentId", equipmentId))
                        finish()
                    }
                })
            }
            deviceDataResult.observe(this@DeviceAddActivity){
                parseState(it, {
                    it?.let {
                        device = it
                        initUIData(it)
                    }
                })
            }
        }
    }

    override fun onDestroy() {
        KeyboardUtils.unregisterSoftInputChangedListener(window)
        super.onDestroy()
    }

}